#include "CalculatorServer.h"
#include "Protocol.h"
#include <memory>

using namespace std;
using namespace server;

static void usage(const string& process) {
    cout << "\nusage:\n\t" << process << " local_port\n" << endl;
}

static void webCalculateService(const Request& request, Response& response) {
    switch (request._oper) {
    case '+':
        response._result = request._num1 + request._num2;
        break;

    case '-':
        response._result = request._num1 - request._num2;
        break;

    case '*':
        response._result = request._num1 * request._num2;
        break;

    case '/': {
        if (request._num2 == 0) {
            response._exitcode = DIVIDE_ZERO;
        }
        else {
            response._result = request._num1 / request._num2;
        }
    }
        break;

    case '%':
        if (request._num2 == 0) {
            response._exitcode = MODE_ZERO;
        }
        else {
            response._result = request._num1 % request._num2;
        }
        break;

    default:
        response._exitcode = OPERATOR_ERROR;
        break;
    }
    
} //@end void webCalculateService(const Request& request, Response& response)

//@usage ./TcpServer local_port
int main(int argc, char** argv) {
    if (argc != 2) {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    uint16_t port = (uint16_t)atoi(argv[1]);

    unique_ptr<CalculatorServer> tcp_server(new CalculatorServer(webCalculateService, port));
    tcp_server->initServer();

    tcp_server->start();
    
    return 0;
}